/**
 * Maven Helper 扩展 - 依赖树生成测试
 * 这个脚本演示了改进后的树生成逻辑
 */
console.log('===== 测试Maven Helper扩展修复 =====');

// 模拟一些示例依赖数据
const sampleDependencies = [
    {
        groupId: "org.springframework.boot",
        artifactId: "spring-boot-starter",
        version: "2.5.5",
        path: [],
        conflicts: []
    },
    {
        groupId: "org.springframework.boot",
        artifactId: "spring-boot",
        version: "2.5.5",
        path: ["org.springframework.boot:spring-boot-starter"],
        conflicts: []
    },
    {
        groupId: "org.springframework",
        artifactId: "spring-core",
        version: "5.3.10",
        path: ["org.springframework.boot:spring-boot-starter", "org.springframework.boot:spring-boot"],
        conflicts: []
    },
    {
        groupId: "org.springframework",
        artifactId: "spring-web",
        version: "5.3.10",
        path: ["org.springframework.boot:spring-boot-starter"],
        conflicts: [
            {
                groupId: "org.springframework",
                artifactId: "spring-web",
                version: "5.3.9",
                path: ["org.springframework.boot:spring-boot-starter-web"]
            }
        ]
    },
    {
        groupId: "junit",
        artifactId: "junit",
        version: "4.13.2",
        path: [],
        scope: "test",
        conflicts: []
    },
    {
        groupId: "org.hamcrest",
        artifactId: "hamcrest-core",
        version: "1.3",
        path: ["junit:junit"],
        conflicts: []
    }
];

/**
 * 简化的HTML转义函数
 */
function escapeHtml(text) {
    return String(text)
        .replace(/&/g, '&amp;')
        .replace(/</g, '&lt;')
        .replace(/>/g, '&gt;')
        .replace(/"/g, '&quot;')
        .replace(/'/g, '&#039;');
}

/**
 * 生成依赖树 HTML (标准实现)
 */
function generateSimplifiedDependencyTreeHtml(dependencies) {
    console.log("生成简化依赖树...");
    const rootDeps = dependencies.filter(d => d.path.length === 0);
    console.log(`根依赖数量: ${rootDeps.length}`);
    
    // 初始化HTML
    let html = `
        <div class="tree-view">
    `;
    
    // 构建依赖树函数
    function buildDependencyTree(dep) {
        // 检查是否有冲突
        const hasConflict = dep.conflicts && dep.conflicts.length > 0;
        
        // 创建该层级依赖的HTML
        let depHtml = `
            <div class="root-dep${hasConflict ? ' conflict' : ''}">
                <span class="group-id">${escapeHtml(dep.groupId)}</span>:<span class="artifact-id">${escapeHtml(dep.artifactId)}</span>:<span class="version">${escapeHtml(dep.version)}</span> ${dep.scope ? `<span class="scope">(${escapeHtml(dep.scope)})</span>` : ''}
        `;
        
        // 找到子依赖
        const childDeps = dependencies.filter(d => 
            d.path.length > 0 && 
            d.path[d.path.length - 1] === `${dep.groupId}:${dep.artifactId}`
        );
        
        // 添加子依赖
        if (childDeps.length > 0) {
            for (const childDep of childDeps) {
                const childHasConflict = childDep.conflicts && childDep.conflicts.length > 0;
                depHtml += `
                <div class="dep${childHasConflict ? ' conflict' : ''}">
                    <span class="group-id">${escapeHtml(childDep.groupId)}</span>:<span class="artifact-id">${escapeHtml(childDep.artifactId)}</span>:<span class="version">${escapeHtml(childDep.version)}</span> ${childDep.scope ? `<span class="scope">(${escapeHtml(childDep.scope)})</span>` : ''}
                `;
                
                // 找到孙子依赖
                const grandChildDeps = dependencies.filter(d => 
                    d.path.length > 0 && 
                    d.path[d.path.length - 1] === `${childDep.groupId}:${childDep.artifactId}`
                );
                
                // 添加孙子依赖，最多只展示两个层级
                if (grandChildDeps.length > 0) {
                    for (const grandChildDep of grandChildDeps) {
                        const grandChildHasConflict = grandChildDep.conflicts && grandChildDep.conflicts.length > 0;
                        depHtml += `
                        <div class="dep${grandChildHasConflict ? ' conflict' : ''}">
                            <span class="group-id">${escapeHtml(grandChildDep.groupId)}</span>:<span class="artifact-id">${escapeHtml(grandChildDep.artifactId)}</span>:<span class="version">${escapeHtml(grandChildDep.version)}</span> ${grandChildDep.scope ? `<span class="scope">(${escapeHtml(grandChildDep.scope)})</span>` : ''}
                        </div>
                        `;
                    }
                }
                
                depHtml += `</div>`;
            }
        }
        
        depHtml += `</div>`;
        return depHtml;
    }
    
    // 为每个根依赖构建树
    for (const rootDep of rootDeps) {
        html += buildDependencyTree(rootDep);
    }
    
    html += `</div>`;
    return html;
}

/**
 * 生成简单树视图 HTML (备用实现)
 */
function generateSimpleTreeHtml(dependencies) {
    // 检查依赖数据
    if (!dependencies || !Array.isArray(dependencies)) {
        console.error('无效的依赖数据');
        return '<div class="error-message">无效的依赖数据</div>';
    }

    if (dependencies.length === 0) {
        return '<div class="no-dependencies">没有找到依赖</div>';
    }

    // 获取根依赖
    const rootDeps = dependencies.filter(d => !d.path || d.path.length === 0);
    console.log(`找到${rootDeps.length}个根依赖`);

    let html = `
        <div class="tree-view simple">
            <div class="summary">依赖树总览: ${dependencies.length}个依赖, ${rootDeps.length}个根依赖</div>
            <ul class="root-list">
    `;

    // 处理根依赖
    for (const dep of rootDeps) {
        const hasConflict = dep.conflicts && dep.conflicts.length > 0;
        const version = dep.version || '未指定';
        const scope = dep.scope || 'compile';

        html += `
            <li class="root-dep${hasConflict ? ' conflict' : ''}">
                <div class="dep-line">
                    <span class="dep-name">${escapeHtml(dep.groupId)}:${escapeHtml(dep.artifactId)}</span>
                    <span class="dep-version">${escapeHtml(version)}</span>
                    <span class="dep-scope">${escapeHtml(scope)}</span>
                </div>
                <div class="dep-children">
                    <ul>
        `;
        
        // 查找直接子依赖
        const childDeps = dependencies.filter(d => 
            d.path && d.path.length === 1 && 
            d.path[0] === `${dep.groupId}:${dep.artifactId}`
        );
        
        for (const childDep of childDeps) {
            const childHasConflict = childDep.conflicts && childDep.conflicts.length > 0;
            html += `
                <li${childHasConflict ? ' class="conflict"' : ''}>${escapeHtml(childDep.groupId)}:${escapeHtml(childDep.artifactId)}:${escapeHtml(childDep.version || '未指定')}</li>
            `;
        }
        
        html += `
                    </ul>
                </div>
            </li>
        `;
    }

    html += `
            </ul>
        </div>
    `;
    
    return html;
}

/**
 * 生成应急树视图 (最简单的实现，在其他方法都失败时使用)
 */
function generateEmergencyTreeView(dependencies) {
    console.log("生成应急依赖树视图...");
    
    // 提取根依赖
    const rootDeps = dependencies.filter(d => !d.path || d.path.length === 0);
    const conflictDeps = dependencies.filter(d => d.conflicts && d.conflicts.length > 0);
    
    // 创建一个极简的表格样式视图
    let html = `
        <div class="emergency-tree">
            <div class="summary">
                <strong>依赖总览:</strong> ${dependencies.length} 个依赖, 
                ${rootDeps.length} 个根依赖, 
                ${conflictDeps.length} 个冲突
            </div>
            <div class="note">
                <strong>注意:</strong> 完整依赖树无法显示，仅显示根依赖。
            </div>
            <table class="deps-table">
                <thead>
                    <tr>
                        <th>GroupId</th>
                        <th>ArtifactId</th>
                        <th>Version</th>
                        <th>Scope</th>
                    </tr>
                </thead>
                <tbody>
    `;
    
    // 只添加根依赖
    for (const dep of rootDeps) {
        const hasConflict = dep.conflicts && dep.conflicts.length > 0;
        html += `
            <tr class="${hasConflict ? 'conflict' : ''}">
                <td>${escapeHtml(dep.groupId)}</td>
                <td>${escapeHtml(dep.artifactId)}</td>
                <td>${escapeHtml(dep.version || '未指定')}</td>
                <td>${escapeHtml(dep.scope || 'compile')}</td>
            </tr>
        `;
    }
    
    // 关闭表格
    html += `
                </tbody>
            </table>
            <div class="refresh-container">
                <button class="refresh-btn">
                    刷新依赖树
                </button>
            </div>
        </div>
    `;
    
    return html;
}

/**
 * 改进后的依赖树生成方法
 * 该方法先尝试使用标准实现，如果失败则回退到简化版，最后回退到应急版
 */
function generateDependencyTree(dependencies) {
    console.log("生成依赖树...");
    try {
        // 首先检查输入参数的有效性
        if (!dependencies || !Array.isArray(dependencies)) {
            console.error("无效的依赖数据");
            throw new Error("无效的依赖数据");
        }
        
        if (dependencies.length === 0) {
            console.log("没有找到依赖");
            return '<div class="no-dependencies">没有找到依赖</div>';
        }
        
        // 记录一些基本信息，用于调试
        const rootDepsCount = dependencies.filter(d => !d.path || d.path.length === 0).length;
        console.log(`依赖总数: ${dependencies.length}, 根依赖数: ${rootDepsCount}`);
        
        // 策略1：先尝试使用标准实现
        try {
            console.log("尝试使用标准依赖树生成逻辑");
            
            // 使用标准函数生成树HTML
            const normalTreeHtml = generateSimplifiedDependencyTreeHtml(dependencies);
            
            // 检查生成的HTML是否有效
            if (normalTreeHtml && normalTreeHtml.length > 100) {
                console.log("标准树生成成功，内容长度:", normalTreeHtml.length);
                return normalTreeHtml;
            } else {
                console.warn("标准树生成结果太短，可能无效");
            }
        } catch (err) {
            console.warn("标准依赖树生成出错:", err);
            // 标准方法失败，继续尝试简化版本
        }
        
        // 策略2：尝试使用简化版本
        console.log("尝试使用简化版本的树生成逻辑");
        try {
            const simpleTreeHtml = generateSimpleTreeHtml(dependencies);
            
            // 检查生成的HTML是否有效
            if (simpleTreeHtml && simpleTreeHtml.length > 100) {
                console.log("简化树生成成功，内容长度:", simpleTreeHtml.length);
                return simpleTreeHtml;
            } else {
                console.warn("简化树生成结果太短，可能无效");
            }
        } catch (simpleErr) {
            console.error("简化依赖树生成出错:", simpleErr);
            // 让外层错误处理捕获
        }
        
        // 两种方法都失败，返回最简单的应急显示
        console.error("所有树生成方法都失败，使用应急方案");
        return generateEmergencyTreeView(dependencies);
        
    } catch (error) {
        console.error("依赖树生成错误:", error);
        // 如果出错，返回一个简单的错误提示
        const errorMessage = error instanceof Error ? error.message : String(error);
        return `
            <div class="tree-error">
                <h3>依赖树生成失败</h3>
                <p>错误信息: ${escapeHtml(errorMessage || '未知错误')}</p>
                <p>请尝试刷新或重启扩展</p>
                <button onclick="alert('刷新操作')">
                    刷新依赖分析
                </button>
            </div>
            <style>
                .tree-error {
                    padding: 15px;
                    color: #e51400;
                    border: 1px solid #e51400;
                    border-radius: 5px;
                    margin: 20px;
                }
                .tree-error button {
                    background-color: #0078D7;
                    color: white;
                    border: none;
                    padding: 6px 12px;
                    margin-top: 10px;
                    cursor: pointer;
                }
            </style>
        `;
    }
}

// 执行测试并在控制台输出结果
console.log("\n===== 依赖树生成测试 =====");
try {
    // 标准树生成测试
    console.log("\n[标准树视图测试]");
    const standardTreeHtml = generateSimplifiedDependencyTreeHtml(sampleDependencies);
    console.log("标准树生成结果长度:", standardTreeHtml.length);
    
    // 简化树生成测试
    console.log("\n[简化树视图测试]");
    const simpleTreeHtml = generateSimpleTreeHtml(sampleDependencies);
    console.log("简化树生成结果长度:", simpleTreeHtml.length);
    
    // 应急树视图测试
    console.log("\n[应急树视图测试]");
    const emergencyTreeHtml = generateEmergencyTreeView(sampleDependencies);
    console.log("应急树生成结果长度:", emergencyTreeHtml.length);
    
    // 改进后的树生成逻辑测试
    console.log("\n[改进后的树生成逻辑测试]");
    const improvedTreeHtml = generateDependencyTree(sampleDependencies);
    console.log("改进后树生成结果长度:", improvedTreeHtml.length);
    
    // 错误情况测试
    console.log("\n[错误处理测试 - 空依赖]");
    const emptyResult = generateDependencyTree([]);
    console.log("空依赖结果:", emptyResult);
    
    console.log("\n[错误处理测试 - 故意制造错误]");
    const invalidDependencies = null;
    try {
        generateDependencyTree(invalidDependencies);
    } catch (err) {
        console.log("预期的错误被处理:", err.message);
    }
    
    console.log("\n===== 测试完成 =====");
    console.log("所有测试都成功运行!");
    
    // 创建示例树视图HTML
    const fs = require('fs');
    try {
        const testHtml = `
<!DOCTYPE html>
<html>
<head>
    <title>Maven Helper - 依赖树视图测试结果</title>
    <style>
        body {
            font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
            margin: 20px;
            background-color: #f3f3f3;
            color: #333;
        }
        .container {
            background-color: white;
            border-radius: 5px;
            padding: 20px;
            box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
            margin-bottom: 30px;
        }
        h1, h2 {
            color: #0066cc;
        }
        .tree-view {
            font-family: monospace;
            margin-top: 20px;
        }
        .root-dep {
            margin-bottom: 15px;
            padding-bottom: 5px;
            border-bottom: 1px solid #ddd;
        }
        .dep {
            margin-left: 20px;
            position: relative;
        }
        .dep:before {
            content: '';
            position: absolute;
            left: -15px;
            top: 8px;
            height: 1px;
            width: 10px;
            background-color: #aaa;
        }
        .dep:after {
            content: '';
            position: absolute;
            left: -15px;
            top: 0;
            bottom: 0;
            width: 1px;
            background-color: #aaa;
        }
        .dep:last-child:after {
            bottom: auto;
            height: 8px;
        }
        .conflict {
            color: #e51400;
            font-weight: bold;
        }
        .group-id {
            color: #0077cc;
        }
        .artifact-id {
            color: #6c6c6c;
        }
        .version {
            color: #008000;
        }
        .scope {
            color: #9c27b0;
            font-style: italic;
        }
    </style>
</head>
<body>
    <h1>Maven Helper - 依赖树视图测试结果</h1>
    
    <div class="container">
        <h2>标准树视图</h2>
        ${standardTreeHtml}
    </div>
    
    <div class="container">
        <h2>简化树视图</h2>
        ${simpleTreeHtml}
    </div>
    
    <div class="container">
        <h2>应急树视图</h2>
        ${emergencyTreeHtml}
    </div>
    
    <div class="container">
        <h2>改进后的树视图</h2>
        ${improvedTreeHtml}
    </div>
    
    <div class="container">
        <h2>错误处理</h2>
        ${generateDependencyTree(null)}
    </div>
</body>
</html>
        `;
        
        fs.writeFileSync('test-result.html', testHtml);
        console.log("\n生成的测试结果保存在: test-result.html");
    } catch (fsErr) {
        console.error("保存测试结果HTML时出错:", fsErr);
    }
    
} catch (error) {
    console.error("测试过程中发生错误:", error);
}
